package com.yequan.mybatisframework.config;

import java.util.List;

import org.dom4j.Element;

/***
 * 主要是按照mybatis的语言去解析映射文件
 * 
 * @author think
 *
 */
public class XMLMapperParser {

	private Configuration configuration;

	private String namespace;

	public XMLMapperParser(Configuration configuration) {
		this.configuration = configuration;
	}

	@SuppressWarnings("unchecked")
	public void parse(Element mapperElement) {
		namespace = mapperElement.attributeValue("namespace");

		List<Element> elements = mapperElement.elements("select");
		for (Element selectElement : elements) {
			parseStatement(selectElement);
		}
	}

	private void parseStatement(Element selectElement) {
		// 一个MappedStatement对象，就对应一个select标签
		String id = selectElement.attributeValue("id");
		String parameterType = selectElement.attributeValue("parameterType");
		Class<?> parameterTypeClass = resolveClass(parameterType);

		String resultType = selectElement.attributeValue("resultType");
		Class<?> resultTypeClass = resolveClass(resultType);

		String statementType = selectElement.attributeValue("statementType");

		// SqlSource就是封装了SQL语句
		// 此时封装的SQL语句是没有进行处理的，什么时候处理呢？
		// 处理时机，就是在SqlSession执行的时候
		// SELECT * FROM user WHERE id = #{id}
		String sqlText = selectElement.getTextTrim();
		SqlSource sqlSource = new SqlSource(sqlText);

		String statementId = namespace + "." + id;
		MappedStatement mappedStatement = new MappedStatement(statementId, parameterTypeClass, resultTypeClass,
				statementType, sqlSource);
		configuration.setMappedStatement(statementId, mappedStatement);
	}

	private Class<?> resolveClass(String parameterType) {
		try {
			return Class.forName(parameterType);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		return null;
	}

}
